package org.example.myleet.p539;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Solution {
    public int findMinDifference(List<String> timePoints) {
        int n = timePoints.size();
        int[] minutes = new int[n];
        Iterator<String> iterator = timePoints.listIterator();
        for (int i = 0; i < n; ++i) {
            //全部转化为分钟数
            minutes[i] = getMinutes(iterator.next());
        }
        //排序
        Arrays.sort(minutes);
        int minInterval = Integer.MAX_VALUE;
        for (int i = 1; i < n; ++i) {
            //计算最小间隔
            minInterval = Math.min(minInterval, minutes[i] - minutes[i - 1]);
        }
        //不要忘了最小时间和最大时间之间可能更小，给最小时间加上24小时再计算间隔
        minInterval = Math.min(minInterval, (minutes[0] + 24 * 60) - minutes[n - 1]);
        return minInterval;
    }

    /**
     * 接受HH:MM格式的字符串并计算其包含的分钟数
     */
    private int getMinutes(String time) {
        int hour, minute, result;
        hour = (time.charAt(0) - '0') * 10 + time.charAt(1) - '0';
        minute = (time.charAt(3) - '0') * 10 + time.charAt(4) - '0';
        result = hour * 60 + minute;
        return result;
    }
}
